package com.deluxelx.soul.inn.service.oauth.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deluxelx.soul.inn.bean.user.oauth.AccountDTO;
import com.deluxelx.soul.inn.bean.user.User;
import com.deluxelx.soul.inn.common.result.ResponseCode;
import com.deluxelx.soul.inn.common.util.EncryptionUtil;
import com.deluxelx.soul.inn.common.util.supportIds.SnowflakeId;
import com.deluxelx.soul.inn.mapper.user.UserMapper;
import com.deluxelx.soul.inn.service.oauth.OAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 权限相关服务实现类
 *
 * @author: zihao.liao
 * @date: 2024/1/19 10:22
 */
@Service
@Slf4j
public class OAuthServiceImpl implements OAuthService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private SnowflakeId snowflakeId;

    @Override
    public ResponseCode register(AccountDTO accountDTO) {
        if (userMapper.selectByAccount(accountDTO.getAccount()) > 0) {
            return ResponseCode.ACCOUNT_ALREADY_EXISTS;
        }

        User user = buildUser(accountDTO);
        if (userMapper.insert(user) > 0) {
            return ResponseCode.SUCCESS;
        }
        return ResponseCode.ERROR;
    }

    @Override
    public String login(AccountDTO accountDTO) {
        try {
            if (userMapper.loginCheck(accountDTO.getAccount(), accountDTO.getPassword()) > 0) {
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getAccount, accountDTO.getAccount());
                User user = userMapper.selectOne(queryWrapper);
                return EncryptionUtil.encrypt(user.getId(), user.getAccount(), user.getPassword());
            }
        } catch (Exception e) {
            log.error(e.toString());
            return StrUtil.EMPTY;
        }
        return StrUtil.EMPTY;
    }

    public User buildUser(AccountDTO accountDTO) {
        String userId = snowflakeId.nextStrId();
        LocalDateTime now = LocalDateTime.now();

        User user = new User();
        user.setId(userId);
        user.setAccount(accountDTO.getAccount());
        user.setPassword(accountDTO.getPassword());
        user.setNickName(accountDTO.getNickName());
        user.setAvatar(accountDTO.getAvatar());
        user.setRegisterTime(now);
        user.setCreateTime(now);
        user.setCreateUser(userId);
        user.setUpdateTime(now);
        user.setUpdateUser(userId);
        return user;
    }
}
